
import { ref } from 'vue'
import { type RouteRecordRaw } from 'vue-router'
import { getRouters } from '@/api'
import Layout from '@/layout/index.vue'
import ParentView from '@/components/ParentView/index.vue'
import InnerLink from '@/layout/components/InnerLink/index.vue'
/** 动态路由列表 */
export let routerList: Array<any> = [];

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../views/**/*.vue')
export const usePermissionStore = () => {
  const generateRoutes = async (): Promise<RouteRecordRaw[]> => {
    const res = await getRouters()
    const { data } = res;
    routerList = data ?? [];
    const rdata = JSON.parse(JSON.stringify(data))
    const rewriteRoutes = filterAsyncRouter(rdata, undefined, true)
    return new Promise<RouteRecordRaw[]>((resolve) => resolve(rewriteRoutes))
  }

  /**
   * 遍历后台传来的路由字符串，转换为组件对象
   * @param asyncRouterMap 后台传来的路由字符串
   * @param lastRouter 上一级路由
   * @param type 是否是重写路由
   */
  const filterAsyncRouter = (asyncRouterMap: RouteRecordRaw[], lastRouter?: RouteRecordRaw, type = false): RouteRecordRaw[] => {
    return asyncRouterMap.filter((route: any) => {
      if (type && route.children) {
        route.children = filterChildren(route.children, undefined)
      }
      if (route.component) {
        // Layout ParentView 组件特殊处理
        if (route.component === 'Layout') {
          route.component = Layout
        } else if (route.component === 'ParentView') {
          route.component = ParentView
        } else {
          route.component = loadView(route.component)
        }
      } else if (route.linkUrl?.startsWith("http")) {
        route.component = InnerLink;
        route.props = { src: route.linkUrl }
      }
      if (route.children != null && route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, route, type)
      } else {
        delete route.children
        delete route.redirect
      }
      return true
    })
  }
  const filterChildren = (childrenMap: RouteRecordRaw[], lastRouter?: RouteRecordRaw): RouteRecordRaw[] => {
    let children: RouteRecordRaw[] = []
    childrenMap.forEach((el: any) => {
      if (el.children && el.children.length) {
        if (el.component === 'ParentView' && !lastRouter) {
          el.children.forEach((c: RouteRecordRaw) => {
            c.path = el.path + '/' + c.path
            if (c.children && c.children.length) {
              children = children.concat(filterChildren(c.children, c))
              return
            }
            children.push(c)
          })
          return
        }
      }
      if (lastRouter) {
        el.path = lastRouter.path + '/' + el.path
      }
      children = children.concat(el)
    })
    return children
  }
  return { generateRoutes }
}
export const loadView = (view: string) => {
  let res;
  for (const path in modules) {
    const dir = path.replace(/^\.*/g, "");
    if (dir === view) {
      res = () => modules[path]()
    }
  }
  return res
}